package com.example.logindesign;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.community.content.CommunityStatisticsKuiwenActivity;
import com.event.content.EventListViewActivity;
import com.population.content.PopulationListViewActivity;
import com.readystatesoftware.viewbadger.BadgeView;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Mainmenu extends Activity {
	// webservice 用参数
	private static final String NAMESPACE = "http://tempuri.org/";
	private static final String ENDPOINT = "http://192.168.1.198:1536/CommunitySystemsicWsWF.asmx";
	private String methodName, soapAcion;

	// userid 得到权限用
	private String userid;
	private String authority = "";

	private long exitTime = 0;
	// 下部几个导航按钮
	private ImageButton homeImageButton, personImageButton;

	// 将图片放入数组中
	private int[] mainInterfaceImageIDs = { R.drawable.notepad,
			R.drawable.blinklist, R.drawable.chrome, R.drawable.designfloat,
			R.drawable.designmoo, R.drawable.graph2, R.drawable.skype,
			R.drawable.technorati, R.drawable.setting };

	// 将图片对应的文字内容存入一个数组
	private String[] mainInterfaceStr = { "事件管理", "人口查询", "社区统计", "个人邮件",
			"工作日志", "通知通告", "程序7", "程序8", "程序9" };

	// gridview 相关
	private ArrayList<HashMap<String, Object>> lstItemsArrayList;
	private SimpleAdapter gridviewAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu);
		// sharedpreference中取得相应值
		getValueFromSharedPreferences();
		// 得到相应权限生成菜单
		// new getAuthorityTask().execute();
		// 绑定下面几个导航按钮
		personImageButton = (ImageButton) findViewById(R.id.imagebutton_person);
		final BadgeView bv1 = new BadgeView(this, personImageButton);
		bv1.setText("12");
		bv1.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
		bv1.show();
		personImageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				bv1.toggle();
			}
		});

		GridView gridView = (GridView) findViewById(R.id.gridview_menu);

		// 生成动态数组，传入数据
		lstItemsArrayList = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < mainInterfaceImageIDs.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemsImage", mainInterfaceImageIDs[i]);
			map.put("itemsText", mainInterfaceStr[i]);
			lstItemsArrayList.add(map);
		}

		gridviewAdapter = new SimpleAdapter(this, lstItemsArrayList,
				R.layout.gridview_items, new String[] { "itemsImage",
						"itemsText" }, new int[] { R.id.itemImage,
						R.id.itemText });
		gridView.setAdapter(gridviewAdapter);
		gridviewAdapter.notifyDataSetChanged();

		// 当点击图片时进入相应的操作
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				Intent intent = new Intent();
				// TODO Auto-generated method stub
				HashMap<String, Object> item = (HashMap<String, Object>) arg0
						.getItemAtPosition(position);
				String itemText = item.get("itemsText").toString();
				// Toast.makeText(Mainmenu.this, itemText, Toast.LENGTH_LONG)
				// .show();
				if (itemText.equals("事件管理")) {
					intent.setClass(Mainmenu.this, EventListViewActivity.class);
					startActivity(intent);
					finish();
				}
				if (itemText.equals("社区统计")) {
					intent.setClass(Mainmenu.this,
							CommunityStatisticsKuiwenActivity.class);
					startActivity(intent);
					finish();
				}
				if (itemText.equals("人口查询")) {
					intent.setClass(Mainmenu.this,
							PopulationListViewActivity.class);
					startActivity(intent);
					finish();
				}
				if (itemText.equals("个人邮件")) {
					intent.setClass(Mainmenu.this, EventListViewActivity.class);
					startActivity(intent);
					finish();
				}
				if (itemText.equals("工作日志")) {
					intent.setClass(Mainmenu.this, EventListViewActivity.class);
					startActivity(intent);
					finish();
				}
				if (itemText.equals("通知通告")) {
					intent.setClass(Mainmenu.this, EventListViewActivity.class);
					startActivity(intent);
					finish();
				}

				// switch (position) {
				// case 0:
				// // 跳转到某个listview页面
				// intent.setClass(Mainmenu.this, EventListViewActivity.class);
				// startActivity(intent);
				// finish();
				// break;
				// case 1:
				// // 跳转到某个listview页面
				// intent.setClass(Mainmenu.this,
				// PopulationListViewActivity.class);
				// startActivity(intent);
				// finish();
				// break;
				// case 2:
				// // 跳转到社区统计页面
				// intent.setClass(Mainmenu.this,
				// CommunityStatisticsKuiwenActivity.class);
				// startActivity(intent);
				// finish();
				// break;
				// case 3:
				// Toast.makeText(getBaseContext(),
				// "pic" + (position) + " selected",
				// Toast.LENGTH_SHORT).show();
				// break;
				// case 4:
				// Toast.makeText(getBaseContext(),
				// "pic" + (position) + " selected",
				// Toast.LENGTH_SHORT).show();
				// break;
				// case 5:
				// Toast.makeText(getBaseContext(),
				// "pic" + (position) + " selected",
				// Toast.LENGTH_SHORT).show();
				// break;
				// default:
				// Toast.makeText(getBaseContext(),
				// "木有？pic" + (position) + " selected",
				// Toast.LENGTH_SHORT).show();
				// break;
				// }
			}
		});
	}

	/**
	 * sharedpreference中取得相应值
	 */
	private void getValueFromSharedPreferences() {
		// TODO Auto-generated method stub
		SharedPreferences sharedPreferences = getSharedPreferences("UserInfo",
				Activity.MODE_PRIVATE);
		userid = sharedPreferences.getString("userid", "");
	}

	/***
	 * 根据权限生成菜单
	 * 
	 * @author Administrator
	 * 
	 */
	private class getAuthorityTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String resultString = getMyUnitcodeAboutData();
			String finallyResultString = jsonFormat(resultString);
			return finallyResultString;
		}

		protected void onPostExecute(String finallyResultString) {
			if (finallyResultString.equals("success")) {
				Log.e("权限", "成功得到");
				// 根据权限生成菜单
				if (authority.contains("事件管理")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[0]);
					map.put("itemsText", mainInterfaceStr[0]);
					lstItemsArrayList.add(map);
				}
				if (authority.contains("人口查询")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[1]);
					map.put("itemsText", mainInterfaceStr[1]);
					lstItemsArrayList.add(map);
				}
				if (authority.contains("社区统计")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[2]);
					map.put("itemsText", mainInterfaceStr[2]);
					lstItemsArrayList.add(map);
				}
				if (authority.contains("个人邮件")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[3]);
					map.put("itemsText", mainInterfaceStr[3]);
					lstItemsArrayList.add(map);
				}
				if (authority.contains("工作日志")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[4]);
					map.put("itemsText", mainInterfaceStr[4]);
					lstItemsArrayList.add(map);
				}
				if (authority.contains("通知通告")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[5]);
					map.put("itemsText", mainInterfaceStr[5]);
					lstItemsArrayList.add(map);
				}
				if (true) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("itemsImage", mainInterfaceImageIDs[6]);
					map.put("itemsText", mainInterfaceStr[6]);
					lstItemsArrayList.add(map);
				}

				gridviewAdapter.notifyDataSetChanged();
			}
		}
	}

	/**
	 * 得到权限字符串
	 * 
	 * @return
	 */
	private String getMyUnitcodeAboutData() {
		// TODO Auto-generated method stub
		String resultString = "";
		methodName = "get_user_Model";
		soapAcion = "http://tempuri.org/get_user_Model";
		SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
		// userid
		soapObject.addProperty("userid", userid);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(soapObject);
		envelope.dotNet = true;
		HttpTransportSE transportSE = new HttpTransportSE(ENDPOINT);
		try {
			transportSE.call(soapAcion, envelope);
			if (envelope.getResponse() != null) {
				SoapObject object = (SoapObject) envelope.bodyIn;
				resultString = object.getProperty(0).toString();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("IOException", e.getMessage());
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("XmlPullParserException", e.getMessage());
		}
		return resultString;
	}

	/**
	 * 解析json数据
	 * 
	 * @return
	 */
	private String jsonFormat(String resultString) {
		JSONArray jsonArray;
		try {
			jsonArray = new JSONArray(resultString);
			int len = jsonArray.length();
			JSONObject jsonObject = jsonArray.optJSONObject(0);
			if (jsonObject.optString("Code").equals("1")) {
				// 根据实际从第2组开始取得有关数据
				authority = "";
				for (int i = 1; i < len; i++) {
					jsonObject = jsonArray.optJSONObject(i);
					authority += "," + jsonObject.optString("name");
				}
				return "success";
			} else {
				return "fail";
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "fail";
	}

	/**
	 * 重写keydown事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				Mainmenu.this.finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}